// Copyright (c) 2023 Huawei Device Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::{Consumer, ParallelIterator};
use crate::error::ScheduleError;

pub async fn for_each<P, F>(par_iter: P, f: F) -> Result<(), ScheduleError>
where
    P: ParallelIterator + Send,
    F: Fn(P::Item) + Copy + Sync + Send,
{
    let consumer = ForEachConsumer::new(f);
    par_iter.drive(consumer).await
}

pub struct ForEachConsumer<F> {
    f: F,
}

impl<F> ForEachConsumer<F> {
    fn new(f: F) -> Self {
        Self { f }
    }
}

impl<F, P> Consumer<P> for ForEachConsumer<F>
where
    P: ParallelIterator,
    F: Fn(P::Item),
{
    type Output = ();
    fn consume(&self, par_iter: P) -> Self::Output {
        par_iter.iter().for_each(&self.f)
    }

    fn combine(_a: Self::Output, _b: Self::Output) -> Self::Output {}
}
